<template>
  <div class="h-screen flex bg-gray-50">
    <!-- 侧边栏 -->
    <div class="w-64 bg-white shadow-lg flex flex-col">
      <!-- 顶部 -->
      <div class="p-4 border-b">
        <div class="flex items-center">
          <div class="w-10 h-10 bg-gradient-to-br from-blue-500 to-indigo-600 rounded-xl flex items-center justify-center">
            <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
          </div>
          <div class="ml-3">
            <h2 class="text-lg font-semibold text-gray-900">AI超级智能体</h2>
            <p class="text-sm text-gray-500">多功能AI助手</p>
          </div>
        </div>
      </div>

      <!-- 导航菜单 -->
      <div class="flex-1 p-4">
        <nav class="space-y-2">
          <router-link
            to="/home"
            class="flex items-center p-3 text-gray-700 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
            </svg>
            返回主页
          </router-link>
          <router-link
            to="/love-chat"
            class="flex items-center p-3 text-gray-700 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <svg class="w-5 h-5 mr-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4.318 6.318a4.5 4.5 0 000 6.364L12 20.364l7.682-7.682a4.5 4.5 0 00-6.364-6.364L12 7.636l-1.318-1.318a4.5 4.5 0 00-6.364 0z" />
            </svg>
            恋爱大师
          </router-link>
        </nav>
      </div>

      <!-- 用户信息 -->
      <div class="p-4 border-t">
        <div class="relative" ref="userMenuRef">
          <button
            @click="showUserMenu = !showUserMenu"
            class="flex items-center space-x-3 w-full p-2 rounded-lg hover:bg-gray-100 transition-colors"
          >
            <div class="w-8 h-8 user-avatar rounded-full flex items-center justify-center">
              <span class="text-white text-sm font-medium">{{ userInitial }}</span>
            </div>
            <span class="text-sm text-gray-700 flex-1 text-left">{{ authStore.username }}</span>
          </button>
          
          <!-- 用户菜单 -->
          <div
            v-show="showUserMenu"
            class="absolute bottom-full left-0 mb-2 w-full bg-white rounded-md shadow-lg ring-1 ring-black ring-opacity-5 z-50"
          >
            <div class="py-1">
              <button
                @click="handleLogout"
                class="w-full text-left px-4 py-2 text-sm text-gray-700 hover:bg-gray-100"
              >
                注销登录
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主聊天区域 -->
    <div class="flex-1 flex flex-col">
      <!-- 聊天头部 -->
      <div class="bg-white border-b px-6 py-4">
        <div class="flex items-center">
          <div class="w-10 h-10 ai-avatar rounded-full flex items-center justify-center">
            <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
          </div>
          <div class="ml-3">
            <h3 class="text-lg font-semibold text-gray-900">AI超级智能体</h3>
            <p class="text-sm text-gray-500">在线 • 具备强大的推理和工具调用能力</p>
          </div>
        </div>
      </div>

      <!-- 欢迎界面或聊天记录 -->
      <div class="flex-1 overflow-hidden">
        <!-- 首次进入欢迎界面 -->
        <div v-if="messages.length === 0" class="h-full flex flex-col items-center justify-center p-8">
          <div class="w-16 h-16 ai-avatar rounded-full flex items-center justify-center mb-6">
            <svg class="w-8 h-8 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
          </div>
          <h2 class="text-2xl font-bold text-gray-900 mb-4">AI超级智能体</h2>
          <p class="text-gray-600 text-center max-w-md leading-relaxed">
            我是您的AI超级助手，具备强大的推理能力和工具调用功能。我可以帮您处理各种复杂任务，从文本创作到数据分析，从代码编写到问题求解。
          </p>
        </div>

        <!-- 聊天记录 -->
        <div v-else class="h-full overflow-y-auto p-6" ref="chatContainer">
          <div class="max-w-4xl mx-auto space-y-6">
            <!-- 开启新对话按钮 -->
            <div class="flex justify-center mb-4">
              <button
                @click="startNewConversation"
                class="inline-flex items-center px-4 py-2 bg-white border border-gray-300 rounded-full text-sm text-gray-700 hover:bg-gray-50 transition-colors"
              >
                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                </svg>
                开启新对话
              </button>
            </div>
            
            <div
              v-for="(message, index) in messages"
              :key="index"
              class="flex"
              :class="message.type === 'user' ? 'justify-end' : 'justify-start'"
            >
              <!-- AI消息 -->
              <div v-if="message.type === 'ai'" class="flex items-start max-w-[80%]">
                <div class="w-8 h-8 ai-avatar rounded-full flex items-center justify-center mr-3 flex-shrink-0">
                  <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
                  </svg>
                </div>
                <div class="chat-bubble chat-bubble-ai">
                  <div v-if="message.loading" class="loading-dots">
                    <div class="loading-dot"></div>
                    <div class="loading-dot"></div>
                    <div class="loading-dot"></div>
                  </div>
                  <MarkdownRenderer v-else :content="message.content" class="text-left" />
                </div>
              </div>

              <!-- 用户消息 -->
              <div v-else class="flex items-start max-w-[80%]">
                <div class="chat-bubble chat-bubble-user">
                  <div class="text-right">{{ message.content }}</div>
                </div>
                <div class="w-8 h-8 user-avatar rounded-full flex items-center justify-center ml-3 flex-shrink-0">
                  <span class="text-white text-xs font-medium">{{ userInitial }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="bg-white border-t p-6">
        <div class="max-w-4xl mx-auto">
          <div class="flex space-x-4">
            <div class="flex-1 relative">
              <textarea
                v-model="inputMessage"
                @keydown="handleKeyDown"
                placeholder="请输入您想要咨询的问题..."
                class="w-full p-4 border border-gray-300 rounded-lg resize-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                rows="1"
                style="min-height: 56px; max-height: 200px;"
                :disabled="isLoading"
              ></textarea>
            </div>
            <div class="flex space-x-2">
              <button
                @click="toggleNetworkSearch"
                :class="[
                  'px-4 py-3 rounded-lg border transition-colors flex items-center justify-center',
                  networkSearch 
                    ? 'bg-blue-500 text-white border-blue-500' 
                    : 'bg-white text-gray-700 border-gray-300 hover:bg-gray-50'
                ]"
                :disabled="isLoading"
                title="联网搜索"
              >
                <svg class="w-5 h-5 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
                <span class="text-xs">联网搜索</span>
              </button>
              <button
                @click="isLoading ? handleAbort() : sendMessage()"
                :disabled="!isLoading && !inputMessage.trim()"
                :class="[
                  'px-6 py-3 rounded-lg transition-colors flex items-center justify-center',
                  isLoading 
                    ? 'bg-red-500 text-white' 
                    : inputMessage.trim() 
                      ? 'bg-blue-500 text-white hover:bg-blue-600'
                      : 'bg-gray-300 text-gray-500 cursor-not-allowed'
                ]"
                aria-label="发送/结束"
              >
                <svg v-if="isLoading" class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                </svg>
                <svg v-else class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import { createManusSSEConnection, createChat } from '../api/index'
import MarkdownRenderer from '../components/MarkdownRenderer.vue'

const router = useRouter()
const authStore = useAuthStore()

const messages = ref([])
const inputMessage = ref('')
const isLoading = ref(false)
const showUserMenu = ref(false)
const userMenuRef = ref(null)
const chatContainer = ref(null)
const networkSearch = ref(false)
const abortController = ref(null)

// 用户名首字母
const userInitial = computed(() => {
  return authStore.username ? authStore.username.charAt(0).toUpperCase() : 'U'
})

// 切换联网搜索
const toggleNetworkSearch = () => {
  networkSearch.value = !networkSearch.value
}

// 发送消息
const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage = inputMessage.value.trim()
  const messageToSend = networkSearch.value ? `联网搜索：${userMessage}` : userMessage
  
  // 添加用户消息
  messages.value.push({
    type: 'user',
    content: userMessage
  })

  // 添加AI加载消息
  const aiMessageIndex = messages.value.length
  messages.value.push({
    type: 'ai',
    content: '',
    loading: true
  })

  inputMessage.value = ''
  isLoading.value = true

  // 滚动到底部
  await nextTick()
  scrollToBottom()

  try {
    // 创建SSE连接 - Manus聊天需要在每次响应后添加换行
    const controller = createManusSSEConnection(
      messageToSend,
      (data) => {
        // 只取data:后面的内容，兼容有无空格
        const cleanData = data.replace(/^data:\s?/, '').trim();
        if (cleanData) {
          messages.value[aiMessageIndex].loading = false
          messages.value[aiMessageIndex].content += cleanData + '\n'
          nextTick(() => scrollToBottom())
        }
      },
      (error) => {
        console.error('SSE连接错误:', error)
        messages.value[aiMessageIndex].loading = false
        if (error?.limit) {
          messages.value[aiMessageIndex].content = error.message
        } else {
          messages.value[aiMessageIndex].content = '抱歉，连接出现问题，请稍后重试。'
        }
        isLoading.value = false // 确保报错后可用
      },
      () => {
        // 完成
        isLoading.value = false
        messages.value[aiMessageIndex].loading = false
        // 清理末尾多余的换行
        messages.value[aiMessageIndex].content = messages.value[aiMessageIndex].content.trim()
      }
    )
    abortController.value = controller // 保存controller
  } catch (error) {
    console.error('发送消息失败:', error)
    messages.value[aiMessageIndex].loading = false
    messages.value[aiMessageIndex].content = '抱歉，发送消息失败，请稍后重试。'
    isLoading.value = false // 确保报错后可用
  }
}

// 键盘事件处理
const handleKeyDown = (event) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  if (chatContainer.value) {
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight
  }
}

// 注销处理
const handleLogout = () => {
  authStore.logout()
  router.push('/login')
  showUserMenu.value = false
}

// 点击外部关闭用户菜单
const handleClickOutside = (event) => {
  if (userMenuRef.value && !userMenuRef.value.contains(event.target)) {
    showUserMenu.value = false
  }
}

// 开启新对话
const startNewConversation = () => {
  // 清空当前对话
  messages.value = []
  inputMessage.value = ''
  isLoading.value = false
  
  console.log('🔄 Manus开启新对话')
  
  // 滚动到顶部
  scrollToBottom()
}

// 处理中止
const handleAbort = () => {
  // 终止SSE流
  if (abortController.value && typeof abortController.value.abort === 'function') {
    abortController.value.abort()
  }
  isLoading.value = false
  // 给AI消息加"回复已终止"标记
  const lastAiMsg = [...messages.value].reverse().find(m => m.type === 'ai' && m.loading)
  if (lastAiMsg) {
    lastAiMsg.loading = false
    lastAiMsg.content += '\n[回复已终止]'
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})
</script> 